#include "IsmDemoFunctions.h"


TMap<AActor*, int32> DefaultMap;
TMap<AActor*, int32, TPerformanceFirstSetAllocator<> > PerformanceFirstMap;
TArray<AActor*> Actors;

void UIsmDemoFunctions::CreateTestActor(const UObject* WorldContextObject)
{
	DefaultMap.Empty();
	PerformanceFirstMap.Empty();
	PerformanceFirstMap.Reserve(10000);
	Actors.Empty();
	UWorld* World = WorldContextObject->GetWorld();
	int32 ActorNumber = 1000;
	for (int32 Index = 0; Index < ActorNumber; Index++)
	{
		AActor* Actor = World->SpawnActor<AActor>();
		DefaultMap.Add(Actor, Index);
		PerformanceFirstMap.Add(Actor, Index);
		Actors.Add(Actor);
	}
}

DECLARE_CYCLE_STAT(TEXT("IsmDemoFunctions-TestFind1"), STAT_TestFind1, STATGROUP_Game);
DECLARE_CYCLE_STAT(TEXT("IsmDemoFunctions-TestFind2"), STAT_TestFind2, STATGROUP_Game);
DECLARE_CYCLE_STAT(TEXT("IsmDemoFunctions-TestFind3"), STAT_TestFind3, STATGROUP_Game);

void UIsmDemoFunctions::TestFind()
{
	int32 TotalCount = 0;
	{
		for (int32 Index = 0; Index < 10; Index++)
		{
			for (const AActor* Actor : Actors)
			{
				CONDITIONAL_SCOPE_CYCLE_COUNTER(STAT_TestFind1, IsInGameThread());
				if (auto Value = DefaultMap.Find(Actor) )
				{
					TotalCount += *Value;
				}
				else
				{
					UE_LOG(LogTemp, Error, TEXT("Error %s"), *Actor->GetName());
				}
			}
		}
	}
	UE_LOG(LogTemp, Log, TEXT("TotalCount= %d"), TotalCount );
	TotalCount = 0;
	{
		for (int32 Index = 0; Index < 10; Index++)
		{
			for (const AActor* Actor : Actors)
			{
				CONDITIONAL_SCOPE_CYCLE_COUNTER(STAT_TestFind2, IsInGameThread());
				if (auto Value = PerformanceFirstMap.Find(Actor) )
				{
					TotalCount += *Value;
				}
				else
				{
					UE_LOG(LogTemp, Error, TEXT("Error %s"), *Actor->GetName());
				}
			}
		}
	}
	UE_LOG(LogTemp, Log, TEXT("TotalCount= %d"), TotalCount );

	{
		CONDITIONAL_SCOPE_CYCLE_COUNTER(STAT_TestFind3, IsInGameThread());

		for (int32 Index = 0; Index < 10; Index++)
		{
			int32 ActorIndex = 0;
			for (const AActor* Actor : Actors)
			{
				if (Actors[ActorIndex])
				{
					TotalCount += ActorIndex;
				}
				ActorIndex ++;
			}
		}
	}
	UE_LOG(LogTemp, Log, TEXT("TotalCount= %d"), TotalCount );
}

